<template>
  <div class="workflow-process-page">
    <h2>流程定义管理</h2>
    <el-button type="primary" @click="onAdd" v-if="hasPermission(WorkflowAuth.PROCESS_META_ADD)">新建流程</el-button>
    <el-table :data="tableData" :loading="loading" style="width: 100%" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="流程名称" />
      <el-table-column prop="processKey" label="流程Key" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button size="small" @click="onEdit(row)" v-if="hasPermission(WorkflowAuth.PROCESS_META_EDIT)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(row)" v-if="hasPermission(WorkflowAuth.PROCESS_META_DEL)">删除</el-button>
          <el-button size="small" @click="onDesignProcess(row)" v-if="hasPermission(WorkflowAuth.PROCESS_META_EDIT)">流程设计</el-button>
          <el-button size="small" type="success" @click="onDeploy(row)">自动部署</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="fetchList"
      @size-change="fetchList"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      style="margin-top: 16px;"
    />
    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="editVisible" :title="dialogTitle" width="400px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="流程Key" prop="processKey">
          <el-input v-model="editForm.processKey" placeholder="请输入流程Key" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="onEditSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- G6 设计器弹窗 -->
    <el-dialog v-model="g6Visible" :title="dialogTitle+'-流程设计'" width="80%">
      <div ref="g6Container" style="height: 500px;"></div>
      <template #footer>
        <el-button @click="g6Visible = false">取消</el-button>
        <el-button type="primary" @click="onG6Save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import * as G6 from '@antv/g6'
import { getProcessList, addProcess, editProcess, deleteProcesses, getProcessDetail } from '@/api/workflow/process.api'
import { deployProcessMeta } from '@/api/workflow/processMeta.api'
import { WorkflowAuth } from '@/auth/workflow/workflow.auth'
import { usePermission } from '@/hooks/web/usePermission'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon/Icon.vue'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

const router = useRouter()
const { hasPermission } = usePermission()

const tableData = ref([])
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

const editVisible = ref(false)
const editForm = ref({ name: '', processKey: '', key: '', status: '0' })
const editFormRef = ref()
const editRules = {
  name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }],
  processKey: [{ required: true, message: '请输入流程Key', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}
const dialogTitle = ref('')
let editingId = null

const g6Visible = ref(false)
const g6Container = ref(null)
let graph = null

function fetchList() {
  loading.value = true
  getProcessList({ pageNum: pageNum.value, pageSize: pageSize.value }).then(res => {
    tableData.value = res?.items || []
    total.value = res?.total || 0
  }).finally(() => loading.value = false)
}
function onSelectionChange(val) { selectedRows.value = val }
function onAdd() {
  dialogTitle.value = '新建流程'
  editForm.value = { name: '', processKey: '', key: '', status: '0' }
  editingId = null
  editVisible.value = true
}
function onEdit(row) {
  dialogTitle.value = '编辑流程'
  getProcessDetail(row.id).then(res => {
    editForm.value = { ...res.data }
    editingId = row.id
    editVisible.value = true
  })
}
function onEditSave() {
  editFormRef.value.validate((valid) => {
    if (!valid) return
    const data = { ...editForm.value }
    if (editingId) {
      editProcess({ ...data, id: editingId }).then(() => {
        editVisible.value = false
        fetchList()
      })
    } else {
      addProcess(data).then(() => {
        editVisible.value = false
        fetchList()
      })
    }
  })
}
function onDelete(row) {
  deleteProcesses([row.id]).then(fetchList)
}
function onDesignProcess(row) {
  router.push({ path: '/workflow/process/designer', query: { ...row } })
}
function onDesign(row) {
  dialogTitle.value = row.name
  g6Visible.value = true
  nextTick(() => {
    if (!graph) {
      graph = new G6.Graph({
        container: g6Container.value,
        width: 800,
        height: 500,
        // ...其他G6配置
      })
    }
    getProcessDetail(row.id).then(res => {
      graph.data(res.data?.graphData || { nodes: [], edges: [] })
      graph.render()
      editingId = row.id
    })
  })
}
function onG6Save() {
  if (!graph) return
  const data = graph.save()
  editProcess({ id: editingId, graphData: data }).then(() => {
    g6Visible.value = false
    ElMessage.success('流程设计已保存')
  })
}
function onDeploy(row) {
  deployProcessMeta(row.id).then(res => {
    console.log(res);
    
    if (res.code === 200) {
      ElMessage.success(res.msg || '部署成功')
    } else {
      ElMessage.error(res.msg || '部署失败')
    }
    fetchList()
  }).catch(e => {
    ElMessage.error(e?.msg || '部署失败')
  })
}
onMounted(fetchList)
</script>
<style scoped>
.workflow-process-page { padding: 24px; }
</style>
